<template>
    <!-- <tm-app class="app" >
        <view class="header" :style="{ paddingTop: systemInfo.statusBarHeight + 'px' }">
            <image src="../../static/firends/right.png" class="right" @tap="goBack"></image>
            <text class="firend">撰写评论</text>
            <view class="shuoming"></view>
        </view>
        <view class="zong-ping">
            <view class="title-header">
                总评
                <view class="back-info"></view>
            </view>
            <view class="pingjia-img">
                <view class="pingjia-title" v-for="(item, index) in state.scoreList" :key="index"
                    @click="onGetScoreListItem(item, index)">
                    <image :src="item.istype ? item.url : item.defult" class="happy"></image>
                    <view class="pingjia">{{ item.text }}</view>
                </view>
            </view>
        </view>
        <view class="pingjia-input">
            <view class="title-header">
                评价
                <view class="back-info"></view>
            </view>
            <textarea class="textar" placeholder="请输入评论，不超过500字" v-model="state.comment"></textarea>
        </view>
        <view class="pingjia-image">
            <view class="title-header">
                上传照片
                <view class="back-info"></view>
            </view>
            <view class="images-list">
                <view class="image-info" v-for="(item, index) in state.imgurlist">
                    <image :src="item" class="touxiang"></image>
                    <view class="shanchu" @click="deleteImg(index)">
                        <image src="../../static/rate/shanchu.png" class=""></image>
                    </view>
                </view>
                <view class="btns" @click="choseImage" v-if="state.imgurlist.length < 6">
                    <image src="../../static/rate/paizhao.png" class="paizhao"></image>
                </view>
            </view>
        </view>
        <view class="title-mes">
            <view>客观真实的评价能帮助其他胖友做出决策，</view>
            <view>请勿发布非法信息和图片！</view>
        </view>
        <view class="btn" @click="onuserAppraiseAdd">发布</view>
    </tm-app> -->
    <tm-app class="createCircle">

        <view style="background:#fff;width:750rpx;" :style="{height:systemInfo.statusBarHeight + 'px'}"></view>

        <view
            class="content"
            :style="{ top: systemInfo.statusBarHeight + 'px' }"
        >
            <tm-navbar
                style="background-color: #fff"
                :height="50"
                :margin="[0, 0]"
                :padding="[0, 0]"
                :isPlace="false"
                :fontSize="32"
                :title="titleText"
                :transprent="true"
            >
            </tm-navbar>

            <scroll-view class="scr" :scroll-y="true">
                <view class="zong-ping">
                    <view class="title-header">
                        <text class="text">总评</text>
                        <view class="back-info"></view>
                    </view>
                    <view class="pingjia-img">
                        <view
                            class="pingjia-title"
                            v-for="(item, index) in state.scoreList"
                            :key="index"
                            @click="onGetScoreListItem(item, index)"
                        >
                            <image
                                :src="item.istype ? item.url : item.defult"
                                class="happy"
                            ></image>
                            <view class="pingjia">{{ item.text }}</view>
                        </view>
                    </view>
                </view>
                <view class="pingjia-input">
                    <view class="title-header">
                        <text class="text">评价</text>
                        <view class="back-info"></view>
                    </view>
                    <textarea
                        class="textar"
                        @input="checkLength(280)"
                        placeholder="请输入评论，不超过140字"
                        v-model="state.comment"
                    ></textarea>
                </view>
                <view class="pingjia-image">
                    <view class="title-header">
                        <text class="text">上传照片</text>
                        <view class="back-info"></view>
                    </view>
                    <view class="images-list">
                        <view
                            class="image-info"
                            v-for="(item, index) in state.imgurlist"
                        >
                            <image :src="item" :id="`touxiang${index}`" class="touxiang" @tap="previewImage('touxiang',index,state.imgurlist)"></image>

                            <view class="shanchu d-flex a-center j-center">
                                <image
                                    @tap="deleteImg(index)"
                                    class="image-del-icon"
                                    src="@/static/image/upload-image-del.png"
                                ></image>
                            </view>
                        </view>
                        <view
                            class="btns"
                            @click="choseImage"
                            v-if="state.imgurlist.length < 6"
                        >
                            <image
                                src="../../static/rate/paizhao.png"
                                class="paizhao"
                            ></image>
                        </view>
                    </view>
                </view>
                
            </scroll-view>


            <view class="btn_bottom_box">
				<view class="title-mes">
				    <view>客观真实的评价能帮助其他胖友做出决策，</view>
				    <view>请勿发布非法信息和图片！</view>
				</view>
                <view class="btn_main_r" @tap="onuserAppraiseAdd">
                    <text class="text">发布评价</text>
                </view>
                <view class="bottom_seat"></view>
            </view>


            <!-- <tm-button class="btn_main w-center" :width="690" :shadow="0" :linear-color="['#64F1C5', '#29DBA3']"
                linear="left" :fontSize="32" fontColor="#ffffff" @tap="onuserAppraiseAdd" label="发布"></tm-button> -->
        </view>

        <imagePreview ref="preview"></imagePreview>
    </tm-app>
</template>
<script setup lang="ts">
import { ref, reactive, computed, onMounted, handleError } from "vue";
import { onReady, onShow, onLoad } from "@dcloudio/uni-app";
import { systemInfo as systemInfoStore } from "@/store/systemInfo";
import { userData as userDataStore } from "@/store/userData";
import { userAppraiseAdd } from "@/api/api";
import { BASE_URL } from "@/api/request";
import { showLoading, closeLoading, wait } from "@/utils/utils";
import imagePreview from "@/components/imagePreview.vue";
import { getHDImages } from '@/utils/format';
import { chooseImage } from "@/utils/utils";

const userData: any = userDataStore();
const systemInfo: any = systemInfoStore();
const titleText: any = ref("撰写评价");
const state: any = reactive({
    toUserId: "",
    comment: "",
    scoreList: [
        {
            url: "/static/rate/bab.png",
            defult: "/static/rate/bab2.png",
            score: "1",
            text: "极差的",
            istype: false,
        },
        {
            url: "/static/rate/sm.png",
            defult: "/static/rate/sm2.png",
            score: "2",
            text: "不错",
            istype: false,
        },
        {
            url: "/static/rate/happy.png",
            defult: "/static/rate/happy2.png",
            score: "3",
            text: "惊艳的",
            istype: false,
        },
    ],
    score: "",
    imgurlist: [],
});

const preview = ref();
const previewImage = (idPre:string,index:number,urls:any) => {

	uni.createSelectorQuery().selectAll(`#${idPre}${index}`).boundingClientRect().exec((ret)=>{
	   let params = {
        idPre,
	   	startInfo:ret[0],//图片的初始大小与位置
	   	index:index,//当前图片地址
	   	urls:getHDImages(urls)//预览集合图片地址
	   }
	   preview.value.open(params);
	});
}

const checkLength = (maxLength: number) => {
    let content = state.comment;
    let str = "";
    let len = 0;
    for (var i = 0; i < content.length; i++) {
        //正则表达式判断中文
        if (/[\u4e00-\u9fa5]/.test(content[i])) {
            len += 2;
        } else {
            len++;
        }

        if (len <= maxLength) {
            str += content[i];
        }
    }
    nextTick(() => {
        state.comment = str;
    });
};

// 选取总评
const onGetScoreListItem = (item: any, index: any) => {
    console.log(item);
    state.score = item.score;
    for (let i in state.scoreList) {
        if (state.scoreList[i].istype === true) {
            state.scoreList[i].istype = false;
        }
    }
    state.scoreList[index].istype = true;
};
onLoad((options: any) => {
    state.toUserid = options.toUserid;
});

let loading = false;
// 提交评论
const onuserAppraiseAdd = () => {
    if (state.score === "") {
        uni.showToast({
            icon: "none",
            title: "总评不能为空",
            duration: 1500,
        });
        return;
    }

    if(loading){
        return;
    }

    loading = true;
    showLoading();
    const imageUrl: any = state.imgurlist.join();
    userAppraiseAdd({
        toUserId: state.toUserid,
        userId: userData.id,
        comment: state.comment,
        score: state.score,
        imageUrl,
    }).then((res: any) => {
        console.log(res);
        closeLoading();
        const { flag, data } = res;
        if (flag !== 1) {
            uni.showToast({
                icon: "none",
                title: "请稍后再试",
                duration: 1500,
            });
            return;
        }
        console.log(data);

        uni.showToast({
                icon: "success",
                title: "已发布",
                duration: 1500,
        });

        setTimeout(() => {
            loading = false;
            uni.navigateBack();
        }, 1500);
    });
};
// 删除图片
const deleteImg = (index: number) => {
    state.imgurlist.splice(index, 1);
};
// 上传图片
const choseImage = () => {
    chooseImage({
        success: (chooseImageRes) => {
            const token = uni.getStorageSync("api_token");
            const tempFilePaths = chooseImageRes.tempFilePaths;
            console.log("chooseImageRes");
            console.log(chooseImageRes);
            showLoading();
            uni.uploadFile({
                header: {
                    token,
                },
                url: `${BASE_URL}/file/upload`, //仅为示例，非真实的接口地址
                filePath: tempFilePaths[0],
                name: "file",
                formData: {
                    isCompress: 1,
                },
                success: (uploadFileRes) => {
                    let res: any;
                    closeLoading();
                    try {
                        res = JSON.parse(uploadFileRes.data);
                    } catch (error) {
                        uni.showToast({
                            icon: "none",
                            title: "请稍后再试",
                            duration: 1500,
                        });
                        return;
                    }

                    const { flag, data } = res;

                    console.log(flag);

                    if (flag !== 1) {
                        uni.showToast({
                            icon: "none",
                            title: "上传失败,请稍后再试",
                            duration: 1500,
                        });
                        return;
                    }

                    const { fileUrl } = data;
                    console.log(fileUrl);
                    state.imgurlist.push(fileUrl);
                },
                fail() {
                    closeLoading();
                    uni.showToast({
                        icon: "none",
                        title: "上传失败,请稍后再试",
                        duration: 1500,
                    });
                },
            });
        },
    });
};
const goBack = () => {
    uni.navigateBack();
};
</script>
<style lang="scss" scoped>
.createCircle {
    position: relative;
    width: 750rpx;
    height: 100%;


    .shanchu {
                    position: absolute;
                    width: 40rpx;
                    height: 40rpx;
                    right: 10rpx;
                    bottom: 10rpx;
                    background: rgba(0, 0, 0, 0.5);
                    border-radius: 50%;
                    .image-del-icon {
                        width: 32rpx;
                        height: 32rpx;
                    }
                }

    .text {
        position: relative;
        z-index: 10;
    }

    .btn_main {
        position: fixed;
        display: block;
        height: 80rpx;
        border-radius: 40rpx;
        line-height: 80rpx;
        bottom: calc(constant(safe-area-inset-bottom));
        bottom: calc(env(safe-area-inset-bottom));
        z-index: 100;
    }

    .ask {
        width: 32rpx;
        height: 32rpx;
        margin-left: 5rpx;
    }

    .content {
        position: absolute;
        left: 0;
        right: 0;
        bottom: 0;
        background: #f5f5f5;
    }

    .scr {
        position: absolute;
        top: 50px;
        left: 0;
        right: 0;
        bottom: calc(constant(safe-area-inset-bottom) + 180rpx);
        bottom: calc(env(safe-area-inset-bottom) + 180rpx);

        .zong-ping {
            width: 710rpx;
            height: 310rpx;
            background: #ffffff;
            border-radius: 20rpx;
            margin: 20rpx auto;
            margin-bottom: 0;

            .title-header {
                font-size: 34rpx;
                font-family: PingFangSC-Medium, PingFang SC;
                font-weight: 600;
                color: #333333;
                padding: 20rpx 0 22rpx 30rpx;
                box-sizing: border-box;
                position: relative;

                .back-info {
                    width: 70rpx;
                    height: 26rpx;
                    background: linear-gradient(
                        270deg,
                        rgba(73, 243, 210, 0) 0%,
                        #23e2a6 100%
                    );
                    border-radius: 13rpx;
                    position: absolute;
                    left: 32rpx;
                    bottom: 25rpx;
                }
            }

            .pingjia-img {
                display: flex;
                justify-content: space-around;

                .pingjia-title {
                    display: flex;
                    flex-direction: column;
                    align-items: center;

                    .happy {
                        width: 128rpx;
                        height: 128rpx;
                    }

                    .pingjia {
                        font-size: 28rpx;
                        font-family: PingFangSC-Regular, PingFang SC;
                        font-weight: 400;
                        color: #666666;
                        margin-top: 20rpx;
                    }
                }
            }
        }
    }

    .pingjia-input {
        width: 710rpx;
        height: 410rpx;
        background: #ffffff;
        border-radius: 20rpx;
        margin: 20rpx auto;
        margin-bottom: 0;

        .title-header {
            font-size: 34rpx;
            font-family: PingFangSC-Medium, PingFang SC;
            font-weight: 600;
            color: #333333;
            padding: 20rpx 0 22rpx 30rpx;
            box-sizing: border-box;
            position: relative;

            .back-info {
                width: 70rpx;
                height: 26rpx;
                background: linear-gradient(
                    270deg,
                    rgba(73, 243, 210, 0) 0%,
                    #23e2a6 100%
                );
                border-radius: 13rpx;
                position: absolute;
                left: 32rpx;
                bottom: 25rpx;
            }
        }

        .textar {
            width: 670rpx;
            height: 300rpx;
            background: #f5f5f5;
            margin: 0 auto;
            padding: 20rpx;
        }
    }

    .pingjia-image {
        width: 710rpx;
        height: 550rpx;
        background: #ffffff;
        border-radius: 20rpx;
        margin: 20rpx auto;

        .title-header {
            font-size: 34rpx;
            font-family: PingFangSC-Medium, PingFang SC;
            font-weight: 600;
            color: #333333;
            padding: 20rpx 0 22rpx 30rpx;
            box-sizing: border-box;
            position: relative;

            .back-info {
                width: 136rpx;
                height: 26rpx;
                background: linear-gradient(
                    270deg,
                    rgba(73, 243, 210, 0) 0%,
                    #23e2a6 100%
                );
                border-radius: 13rpx;
                position: absolute;
                left: 32rpx;
                bottom: 25rpx;
            }
        }

        .images-list {
            display: grid;
            grid-template-columns: repeat(3, 210rpx);
            grid-gap: 20rpx 20rpx;
            width: 710rpx;
            justify-content: center;

            .btns {
                width: 210rpx;
                height: 210rpx;
                border-radius: 4rpx;
                border: 2rpx dashed #cccccc;
                display: flex;
                align-items: center;
                justify-content: center;

                .paizhao {
                    width: 50rpx;
                    height: 50rpx;
                    border: 2rpx dashed #cccccc;
                }
            }

            .image-info {
                width: 210rpx;
                height: 210rpx;
                position: relative;

                .touxiang {
                    width: 100%;
                    height: 100%;
                    border-radius: 20rpx;
                }

            }
        }
    }

    .title-mes {
		padding-bottom: 10rpx;
        font-size: 24rpx;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #999999;
        text-align: center;
    }
}
</style>
